﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Utility;
using VAdvantage.Classes;
using System.Windows.Data;
using System.Collections;
using System.Data;
using System.Windows.Browser;


namespace VAdvantage.Apps.AForms
{
    public partial class VServer : UserControl, FormPanel
    {
        #region private Variable
        bool isServerRunning = false;
        VLogger log = null;
        // static ViennaServerMgr s_serverMgr = null;
         private FormFrame _frame;
         private int _windowNo = 0;
         string accesskey = DataBase.GlobalVariable.ACCESSKEY;// "caff4eb4fbd6273e37e8a325e19f0991";//hard code
         string appURL = "";

        #endregion

        /// <summary>
        /// Default Constructor
        /// </summary>
        public VServer()
        {
            log = VLogger.GetVLogger(GetType().FullName);

            //if (HtmlPage.Document.DocumentUri.ToString().Contains("/ViennaAdvantage.aspx"))
            //{
            //    appURL = HtmlPage.Document.DocumentUri.ToString().Replace("/ViennaAdvantage.aspx", "");
            //    log.Info(appURL);
            //}
            //else
            //{
            //    appURL = HtmlPage.Document.DocumentUri.ToString();
            //    log.Info(appURL);
            //}
            appURL = Envs.GetApplicationURL();
        }

        public void Init(int windowNo, FormFrame frame)
        {
             _windowNo = windowNo;
            _frame = frame;
            DataBase.GlobalVariable.IsVserver = true;
            InitializeComponent();
            Grid();
              this.Visibility = System.Windows.Visibility.Visible;
            _frame.ContentGrid.Children.Add(this);
            //_frame.Height = App.Current.Host.Content.ActualHeight - 25;
            //_frame.Width = App.Current.Host.Content.ActualWidth;
            _frame.MinHeight = 300;
            _frame.MinWidth = 300;
            vStatusBar.Text = Msg.GetMsg(Envs.GetCtx(), "ClickStart", null);
            var client = AEnv.GetDSPostingClient();
            client.IsServerRunAsync(Envs.GetCtx().GetAD_Client_ID(), appURL, accesskey);
            client.IsServerRunCompleted += (s, ev) =>
            {
                if (ev.Result == null)
                {
                    vdgRequest.ItemsSource = ServerData.GetServerDataList(true);
                    btnStop.IsEnabled = false;
                    vdgRequest.IsReadOnly = false;
                }
                else
                {
                    List<string> para = ev.Result;
                    IList gridCount = ServerData.GetServerDataList(false) as IList;

                    for (int i = 0; i < para.Count; i++)
                    {
                        for (int j = 0; j < gridCount.Count; j++)
                        {
                            if (((ServerData)gridCount[j]).Process.GetKeyID().Equals(para[i]))
                            {
                                ((ServerData)gridCount[j]).Status = "Running";
                                ((ServerData)gridCount[j]).Ischeck = true;
                                break;
                            }
                            continue;
                        }
                    }
                    vdgRequest.ItemsSource = null;
                    vdgRequest.ItemsSource = gridCount;
                    log = VLogger.GetVLogger(GetType().FullName);
                    btnStop.IsEnabled = true;
                    btnStart.IsEnabled = false;
                    vStatusBar.Text = Msg.GetMsg(Envs.GetCtx(), "AlreadyRunning", null);
                    vdgRequest.IsReadOnly = true;
                }
            };
        }

        /// <summary>
        /// Craete grid column 
        /// </summary>
        private void Grid()
        {
            DataGridCheckBoxColumn checkBoxColumn = new DataGridCheckBoxColumn();
            checkBoxColumn.Header = "#";
            checkBoxColumn.Binding = new Binding("Ischeck");

            vdgRequest.Columns.Add(checkBoxColumn);

            DataGridTextColumn Process = new DataGridTextColumn();
            Process.Header = "Process";
            Process.Binding = new Binding("Process");
            vdgRequest.Columns.Add(Process);

            DataGridTextColumn Port = new DataGridTextColumn();
            Port.Header = "Port";
            Port.Binding = new Binding("Port");
            vdgRequest.Columns.Add(Port);

            DataGridTextColumn Status = new DataGridTextColumn();
            Status.Header = "Status";
            Status.Binding = new Binding("Status");
            vdgRequest.Columns.Add(Status);

            DataGridTextColumn StartedAt = new DataGridTextColumn();
            StartedAt.Header = "StartedAt";
            StartedAt.Binding = new Binding("StartedAt");
            vdgRequest.Columns.Add(StartedAt);
            vdgRequest.AutoGenerateColumns = false;
            vdgRequest.ColumnHeaderHeight = 30;

        }

        bool serverOn = true;

        /// <summary>
        /// Sets the status of process in the ListBox
        /// </summary>
        /// <param name="passed">Indicates if all the required processes have been started</param>
        void SetProcessStatus(bool passed)
        {
            IList gridCount = vdgRequest.ItemsSource as IList;
            if (passed)
            {
                for (int i = 0; i < gridCount.Count; i++)
                {
                    if (((ServerData)gridCount[i]).Ischeck)
                    {
                        ((ServerData)gridCount[i]).Status = "Running";

                    }
                    else
                    {
                        ((ServerData)gridCount[i]).Status = "Stopped";
                    }
                }
            }
            else
            {
                for (int i = 0; i < gridCount.Count; i++)
                {
                    ((ServerData)gridCount[i]).Status = "Stopped";
                }
            }
            vdgRequest.ItemsSource = null;

            vdgRequest.ItemsSource = gridCount;
            if (passed)
            {
                vStatusBar.Text = Msg.GetMsg(Envs.GetCtx(), "ServerRunning", null);
            }
            else
            {
                vStatusBar.Text = Msg.GetMsg(Envs.GetCtx(), "ServerStopped", null);
            }
        }


        private void btnStart_Click(object sender, RoutedEventArgs e)
        {

            bool anyChecked = false;
            bool allChecked = true;
            IList gridCount = vdgRequest.ItemsSource as IList;
            List<string> processorCode = new List<string>();

            for (int i = 0; i < gridCount.Count; i++)
            {
                if (((ServerData)gridCount[i]).Ischeck)
                {
                    anyChecked = true;
                    processorCode.Add(Util.GetValueOfString(((ServerData)gridCount[i]).Process.GetKeyID()));
                }

                if (!((ServerData)gridCount[i]).Ischeck)
                {
                    allChecked = false;
                }

            }

            //if (allChecked)
            //{
            //    bool dg = ShowMessage.Ask("You have selected all the processes to run simultaneously. Doing this might consume plenty of memory of your system. " + Environment.NewLine + "Are you sure you want to run all the processes", null, "Run Process", "");
            //    if (!dg)
            //    {
            //        return;
            //    }
            //}

            if (!anyChecked)
            {
                ShowMessage.Info("NoProcessSelected", null, "Info", "", "");
                return;
            }


            Ctx ctx = Envs.GetCtx();
            Dictionary<string, string> dic = (Dictionary<String, string>)ctx.GetMap();
            var client = AEnv.GetDSPostingClient();
            if (serverOn)
            {
                btnStart.IsEnabled = false;
            }
            else
            {
                btnStart.IsEnabled = true;
                return;
            }
            vdgRequest.IsReadOnly = true;
            client.OnServerAsync(dic, ctx.GetAD_Client_ID(), appURL, processorCode, allChecked, Util.GetValueOfBool(chkTraceFile.IsChecked), accesskey);
            client.OnServerCompleted += new EventHandler<DSPosting.OnServerCompletedEventArgs>(client_OnServerCompleted);

        }

        void client_OnServerCompleted(object sender, DSPosting.OnServerCompletedEventArgs e)
        {
            //ifServer Posting strats then start posting button disable
            if (e.Result)
            {
                serverOn = false;
                vdgRequest.IsReadOnly = true;
                btnStop.IsEnabled = true;
                SetProcessStatus(true);
                vStatusBar.Text = Msg.GetMsg(Envs.GetCtx(), "ServerRunning", null);
            }
            else
            {
                serverOn = true;
                vdgRequest.IsReadOnly = false;
                btnStop.IsEnabled = false;
                vStatusBar.Text = Msg.GetMsg(Envs.GetCtx(), "ServerNotRunning", null);
            }
        }

        private void btnStop_Click(object sender, RoutedEventArgs e)
        {
            btnStop.IsEnabled = false; ;
            var client = AEnv.GetDSPostingClient();
            client.StopServerAsync(true, Envs.GetCtx().GetAD_Client_ID(), appURL, accesskey);
            client.StopServerCompleted += (s, ev) =>
                {
                    if (ev.Result)
                    {
                        ShowMessage.Info(Msg.GetMsg(Envs.GetCtx(), "ServerStoped", null), null, "", "");
                        serverOn = true;
                        btnStart.IsEnabled = true;
                        vdgRequest.IsReadOnly = false;
                        //update grid startedAt status=Stop
                        SetProcessStatus(false);
                        vdgRequest.IsReadOnly = false;
                        vStatusBar.Text = Msg.GetMsg(Envs.GetCtx(), "ServerStoped", null);
                    }
                    else
                    {
                        ShowMessage.Info(Msg.GetMsg(Envs.GetCtx(), "ServerNotStoped", null), null, "", "");
                        serverOn = false;
                        vdgRequest.IsReadOnly = true;
                        btnStart.IsEnabled = false; ;
                        btnStop.IsEnabled = true;
                        vdgRequest.IsReadOnly = true;
                        vStatusBar.Text = Msg.GetMsg(Envs.GetCtx(), "ServerNotStoped", null);
                    }
                };


        }

        private void Form_Closed(object sender, EventArgs e)
        {
            DataBase.GlobalVariable.IsVserver = false;
            //DataBase.GlobalVariable.VServerForm = this;

        }

        public void Dispose()
        {
            DataBase.GlobalVariable.IsVserver = false;
            //DataBase.GlobalVariable.VServerForm = this;
        }
    }

    public class ServerData
    {
        #region private Variable


        static String[] mProcessCode = 
        {
            //"AS",
            "SP",
            "AP",
            "AL",
            "RP",
            "WP",
            //"MS"
        };

        static String[] mProcess = 
        {
            //"Application Server",
            "Scheduler",
            "Account Processor",
            "Alert Processor",
            "Request Processor",
            "Workflow Processor",
           // "MSMQ Server"
        };

        static String[] mPOrt = 
        {
           // "2090",
            "Default",
            "Default",
            "Default",
            "Default",
            "Default",
           // "Default"
        };

        static String[] mStatus = 
        {
            //"Stopped",
            "Stopped",
            "Stopped",
            "Stopped",
            "Stopped",
            "Stopped",
           // "Stopped"
        };


        #endregion

        public Boolean Ischeck { get; set; }
        public VAdvantage.Model.ValueNamePair Process { get; set; }
        public String Port { get; set; }
        public String Status { get; set; }
        public String StartedAt { get; set; }

        private ServerData()
        { }
        public ServerData(Boolean ischeck, VAdvantage.Model.ValueNamePair process, String port, String status, String startedAt)
        {
            this.Ischeck = ischeck;
            this.Process = process;
            this.Port = port;
            this.Status = status;
            this.StartedAt = startedAt;
        }

        public static List<ServerData> GetServerDataList(bool checkValue)
        {

            List<ServerData> obj = new List<ServerData>();
            for (int i = 0; i <= mProcess.Length - 1; i++)
            {
                obj.Add(new ServerData(checkValue, new Model.ValueNamePair(mProcessCode[i], mProcess[i]), mPOrt[i], mStatus[i], ""));

            }

            return obj;
        }

    }


}
